package com.ytjj.qmyx.admin.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Shiro权限配置
 * 一定要配置 @Configuration 和 @EnableConfigurationProperties 注解
 *
 */
@Slf4j
@Configuration
public class ShiroConfig {
    @Autowired
    private ShiroRedisProperties shiroRedisProperties;
    /*
     * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     * 配置以下两个bean(DefaultAdvisorAutoProxyCreator(可选)和AuthorizationAttributeSourceAdvisor)即可实现此功能
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
        log.info("advisorAutoProxyCreator");
        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        advisorAutoProxyCreator.setProxyTargetClass(true);
        return advisorAutoProxyCreator;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        log.info("authorizationAttributeSourceAdvisor");
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * 凭证匹配器（由于我们的密码校验交给Shiro的SimpleAuthenticationInfo进行处理了）
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        log.info("hashedCredentialsMatcher");
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 散列算法:这里使用MD5算法;
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 散列的次数，比如散列两次，相当于 md5(md5(""));
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    private AdminAuthenticationFilter adminAuthenticationFilter(){
        log.info("adminAuthenticationFilter");
        return new AdminAuthenticationFilter();
    }

    @Bean
    public JavaUuidSessionIdGenerator sessionIdGenerator() {
        log.info("sessionIdGenerator");
        return new JavaUuidSessionIdGenerator();
    }
    @Bean
    public AdminRealm adminRealm(){
        AdminRealm adminRealm=new AdminRealm();
        adminRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return adminRealm;
    }
    @Bean
    public RedisManager redisManager(){
        RedisManager redisManager=new RedisManager();
        redisManager.setHost(shiroRedisProperties.getHost());
        redisManager.setDatabase(shiroRedisProperties.getDatabase());
        redisManager.setTimeout(shiroRedisProperties.getTimeout());
        if(StringUtils.isNotBlank(shiroRedisProperties.getPassword())) {
            redisManager.setPassword(shiroRedisProperties.getPassword());
        }
        return redisManager;
    }
    @Bean
    public RedisSessionDAO redisSessionDAO(){
        AdminRedisSessionDAO redisSessionDAO=new AdminRedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        redisSessionDAO.setKeyPrefix(shiroRedisProperties.getSessionKeyPrefix());
        redisSessionDAO.setExpire(shiroRedisProperties.getSessionExpire());
        redisSessionDAO.setSessionInMemoryTimeout(shiroRedisProperties.getSessionInMemoryTimeout()*1000);
        redisSessionDAO.setSessionInMemoryEnabled(shiroRedisProperties.isSessionInMemoryEnabled());
        return redisSessionDAO;
    }

    @Bean
    public AdminSessionManager sessionManager(){
        AdminSessionManager adminSessionManager=new AdminSessionManager();
        adminSessionManager.setSessionDAO(redisSessionDAO());
        adminSessionManager.setGlobalSessionTimeout(shiroRedisProperties.getSessionExpire()*1000);
        adminSessionManager.setSessionIdUrlRewritingEnabled(false);
        return adminSessionManager;
    }
    @Bean
    public RedisCacheManager redisCacheManager(){
        RedisCacheManager redisCacheManager=new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        redisCacheManager.setExpire(shiroRedisProperties.getCacheExpire());
        redisCacheManager.setKeyPrefix(shiroRedisProperties.getCacheKeyPrefix());
        redisCacheManager.setPrincipalIdFieldName(shiroRedisProperties.getPrincipalIdFieldName());
        return redisCacheManager;
    }
    @Bean(name="securityManager")
    public SessionsSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setSessionManager(sessionManager());
        securityManager.setCacheManager(redisCacheManager());
        securityManager.setRealm(adminRealm());
        return securityManager;
    }

    @Bean(name = "shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/index.html");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        // 拦截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/admin/login", "anon");                 //不用验证的请求
        filterChainDefinitionMap.put("/app_config/update", "anon");
        filterChainDefinitionMap.put("/order/refundOrdersByRpc", "anon");
        filterChainDefinitionMap.put("/test/**","anon");
        filterChainDefinitionMap.put("/dataStatistics/timing","anon");
        filterChainDefinitionMap.put("/captcha/**", "anon");
        filterChainDefinitionMap.put("/pageDecoration/getPageById", "anon");
        filterChainDefinitionMap.put("/dynamicTopicController/**", "anon");
        filterChainDefinitionMap.put("/order/sumExposureByDynamicId", "anon");
        filterChainDefinitionMap.put("/order/refundCallback", "anon");
        filterChainDefinitionMap.put("/returnGoods/syncReturnRegisterByRpc", "anon");
        filterChainDefinitionMap.put("/returnGoods/syncReturnRegisterByMark", "anon");
        filterChainDefinitionMap.put("/adsExpose/**", "anon");
        filterChainDefinitionMap.put("/callback/app/**", "anon");
        filterChainDefinitionMap.put("/download", "anon");
        filterChainDefinitionMap.put("/channelProduct/updateGoodsStatusByRpc", "anon");
        filterChainDefinitionMap.put("/product/freightTemplate/selectYxFreightTemplate", "anon");
        filterChainDefinitionMap.put("/product/freightTemplate/selectYxFreightTemplateByProductId", "anon");
        filterChainDefinitionMap.put("/product/freightTemplate/selectChainFreightTemplateByProductId", "anon");
        filterChainDefinitionMap.put("/product/freightTemplate/selectDefaultFreightTemplate", "anon");
        filterChainDefinitionMap.put("/returnGoods/saveReturnDuty", "anon");
        filterChainDefinitionMap.put("/returnGoods/syncReturnRegisterById", "anon");
        filterChainDefinitionMap.put("/redisInfoController/**", "anon");
        filterChainDefinitionMap.put("/returnRegister/refundOperaRpc", "anon");
        filterChainDefinitionMap.put("/**", "authc");

        //自定义过滤器
        Map<String, Filter> filterMap = new LinkedHashMap<>();
        filterMap.put("authc", adminAuthenticationFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        //log.debug("shiroRedisProperties={}",shiroRedisProperties.toString());

        return shiroFilterFactoryBean;
    }
}